<?php
/*
+--------------------------------------------------------------------------
|   Anwsion 用户重建 问题关键词 工具
|   ========================================
|   配置本程序后放在根目录运行一次即可
|   ========================================
|   警告: 使用本程序之前请先备份 anwsion 数据库
|   ========================================
|   本程序不对因使用此程序造成的一切损失负责
+---------------------------------------------------------------------------
*/

define('ROOT_PATH', realpath('./'));
require_once (ROOT_PATH . '/system/init.php');
require_once (AWS_PATH . '/config/database.php');

/*
+--------------------------------------------------------------------------
|   警告: 使用本程序之前请先备份 anwsion 数据库
|   ========================================
|   本程序不对因使用此程序造成的一切损失负责
+---------------------------------------------------------------------------
*/

/****** 程序配置 ******/
// 每次导入的问题数量 (服务器负荷较小可以将值设低)
define('QUESTION_PROCESS', 50);
/****** 配置结束 ******/

@set_time_limit(0);

HTTP::no_cache_header();

define('DB_PREFIX_MASTER', $config['prefix']);

$master_db = Zend_Db::factory($config['driver'], $config['master']);

$master_db->query("SET NAMES utf8");

if (intval($_GET['page']) == 0 OR intval($_GET['page']) == 1)
{
	$next_page = 2;
	$limit = 0;
}
else
{
	$next_page = intval($_GET['page']) + 1;
	$limit = ($next_page - 2) * QUESTION_PROCESS;
}

$pa = new Services_Phpanalysis_Phpanalysis('utf-8', 'utf-8', false);
//载入词典
$pa->LoadDict();

$question_list = $master_db->fetchAll("SELECT * FROM " . DB_PREFIX_MASTER . "question LIMIT " . $limit . ", " . QUESTION_PROCESS);

foreach($question_list as $all_key=>$all_val)
{
	//初始化类	
	$question_content=$all_val['question_content'];
	$question_id=$all_val['question_id'];
	
	//执行分词
	$question_content_tmp=clear_point($question_content);
	$pa->SetSource($question_content_tmp);
	$pa->StartAnalysis(true);
	$okresult = $pa->GetFinallyResult(',',false);
	$okresult_array = preg_split("/,/", $okresult);
	if (is_array($okresult_array))
	{
		$master_db->query("DELETE FROM ".DB_PREFIX_MASTER."question_keyword WHERE question_id = " . intval($question_id));					
					
		$okresult_array=array_unique($okresult_array);
		foreach ($okresult_array as $py_key=>$py_val)
		{
			$py_val=trim($py_val);
			{
				if ($py_val)
				{
					if (cjk_strlen($py_val) > 1)
					{
						$master_db->query("INSERT INTO ".DB_PREFIX_MASTER."question_keyword SET keyword='" . addslashes($py_val) . "', question_id='" . $question_id . "',add_time='".mktime()."'");
										
					}
				}
			}
		}					
	}
}


if (sizeof($question_list) == QUESTION_PROCESS)
{
	TPL::assign('message', '正在处理问题关键字, 当前第 ' . $next_page . ' 批 (每批 ' . QUESTION_PROCESS . ' 条)');
	TPL::assign('url_bit', '?page=' . $next_page);
}
else
{
	TPL::assign('message', '全部用户导入完成, 请删除本工具, 并登录  更新数据缓存.');
}

TPL::output('global/show_message');